package com.suse.ecommerce.controller;

import com.github.pagehelper.PageInfo;
import com.suse.ecommerce.pojo.Product;
import com.suse.ecommerce.pojo.Store;
import com.suse.ecommerce.service.ProductService;
import com.suse.ecommerce.uilts.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ProductService productService;


    /**
     * 查询商品
     */
    @RequestMapping(value = "/getProducts",method = RequestMethod.POST)
    public Msg getProducts(@RequestParam(value = "pn", defaultValue="1") int pn, Product product){
        Integer status = new Integer(1);
        PageInfo productList = productService.selectProducts(product,Integer.valueOf(pn),status);
        return Msg.success("200").add("productList",productList);
    }

    @RequestMapping("/getProduct")
    public Msg getProduct(@RequestParam(value = "pn", defaultValue="1") int pn, Product product){
        PageInfo productList = productService.selectProducts(product,Integer.valueOf(pn),null);
        return Msg.success("200").add("productList",productList);
    }
    /**
     *根据id查询商品
     */
    @RequestMapping("/getProductById")
    public Msg getProductById(String id)
    {
        System.out.println(id);
        Product product1 = productService.queryProductById(Integer.valueOf(id));
        return Msg.success("200").add("product",product1);
    }

    @RequestMapping("/addProduct")
    public Msg addProduct(Product product, @SessionAttribute("store")Store store){
        if(store == null) {
            return Msg.error("没有登陆");
        }
        product.setCreateDate(new Date());
        product.setUpdateDate(new Date());
        product.setStoreId(store.getStoreId());
        productService.addProduct(product);
        return Msg.success("插入成功");
    }

    @RequestMapping("/setProductStatus")
    public  Msg setProductStatus(Product product,@SessionAttribute("store")Store store){
        List<Product> product1 = productService.setProductStatus(product);
        if(product1 == null) {
            return Msg.error("错误");
        }else{
            return Msg.success("成功").add("product",product1);
        }
    }

    @RequestMapping("/delProductById")
    public Msg delProductById(Product product){
        if (product.getId() != null) {
            productService.delProduct(product);
            return Msg.success("成功");
        }else {
            return Msg.error("错误");
        }
    }

    @RequestMapping("/updateProduct")
    public Msg updateProduct(Product product){
        if(product.getId() !=null) {
            productService.updateProduct(product);
            return Msg.success("成功");
        }else{
            return Msg.error("错误");
        }
    }
}
